package com.semp.gu.connector.ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.semp.gu.domain.remote.RemoteAlbum;
import com.semp.gu.domain.remote.RemoteGallery;

public class DomainFactory {
	
	private final static Logger	logger	= LoggerFactory.getLogger(DomainFactory.class);
	
	private final static String SOFTLINK_ID = "->";
	public final static String FILE_SEP = "/";

	public final static RemoteGallery parseGalleryTree(String galleryTreeAsString) throws IOException {
		logger.debug("Parsing folder tree: {}", galleryTreeAsString);
		BufferedReader reader = new BufferedReader(new StringReader(galleryTreeAsString));
		
		// Root folder
		String rootFolder = reader.readLine();
		logger.debug("Root folder: {}", rootFolder);
		RemoteGallery remoteGallery = new RemoteGallery(rootFolder);
		
		// Parse tree
		String folder;
		HashMap<String, RemoteAlbum> pathToAlbumMap = new HashMap<String, RemoteAlbum>();
		while ((folder = reader.readLine()) != null ) {
			if (folder.indexOf(SOFTLINK_ID) >= 0) {
				// Do not parse softlinks
				continue;
			} else {
				String name = folder.substring(folder.lastIndexOf(FILE_SEP) + 1);
				String parentName = folder.substring(0, folder.lastIndexOf(FILE_SEP));
				// Create album
				RemoteAlbum remoteAlbum = new RemoteAlbum();
				remoteAlbum.setName(name);
				logger.debug("Created remoteAlbum {}", name);
				// Find parent
				RemoteAlbum parentAlbum = pathToAlbumMap.get(parentName);
				if (parentAlbum != null) {
					parentAlbum.getSubAlbums().add(remoteAlbum);
					remoteAlbum.setParent(parentAlbum);
					logger.debug("{} set as child of {}", name, parentAlbum.getName());
				} else {
					remoteGallery.getAlbums().add(remoteAlbum);
					logger.debug("{} set as main (root) folder", name);
				}
				// Store in map for parent handling
				pathToAlbumMap.put(folder, remoteAlbum);
			}
		}
		
		return remoteGallery;
	}
	
	public final static String computeAlbumPath(RemoteAlbum album) {
		String albumPath = FILE_SEP + album.getName();
		RemoteAlbum parent = album.getParent();
		if (parent != null) {
			albumPath = computeAlbumPath(parent) + albumPath;
		}
		return albumPath;
	}
}
